const express = require('express')
const { query } = require('../db')
const router = express.Router()

//导出模块
module.exports = router

//导入封装模块处理数据
const db = require('../db')
const {formatData} = require('../utils')

const userRouter = require('./user')
router.use('/user',userRouter)

//注册
router.post('/reg',(req,res)=>{
    //post的响应数据为 req.body
    const {username,password} = req.body
    //把用户信息存入数据库,增insert into 表名(属性名)values(值)
    let sql = `insert into user(username,password)values('${username}','${password}')`
    db.query(sql,(result)=>{
        //result作为实参传入回调函数
        if(result.insertId){//如果insertId有值
            res.send(formatData())
        }else{
            res.send(formatData())
        }
    })
})

//登陆
router.post('/login',(req,res)=>{
    const {username,password} = req.query//get请求用query
    //查询用户信息，查select * from 表名 where 用户名 and 密码
    let sql = `select * from user where username='${username}' and password='${password}'`
    db.query(sql,(result)=>{
        if(result.length>0){
            res.send(formatData.success(result))
        }else{
            res.send(formatData.fail())
        }
    })
})


